package com.wits.comet.chat.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.wits.comet.chat.entity.ChatMember;

public class CometContext {
	
	/**
	 * 
	 * inKey:  用户Id
	 * 
	 */
	private static final Map<String,ChatMember> userMap=new HashMap<String,ChatMember>();
	
//    private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
//    
//    private final Lock r = rw.readLock();
//    private final Lock w = rw.writeLock();
	
	private static CometContext cometContext=new CometContext();
	
	private CometContext(){
		
	}
	
	public synchronized static CometContext getInstance() {
		return cometContext;
	}

	
	/**
	 * 
	 * @param memberId 用户id
	 * @param member
	 */
	public synchronized void addMember(String memberId,ChatMember member){
//		w.lock();
		try{
			if(memberId==null){
				return;
			}
			userMap.put(memberId,member);
		}finally{
//			w.unlock();
		}


	}
	
	/**
	 *  
	 * @param memberId 用户id
	 * @return
	 */
	public synchronized ChatMember getMember(String memberId){
//		r.lock();
		try{
			if(memberId==null){
				return null;
			}
			return userMap.get(memberId);
		}finally{
//			r.unlock();
		}

	}
	
	public synchronized void removeMember(String memberId){
//		w.lock();
		try{
			if(memberId==null){
				return;
			}
			ChatMember cm=userMap.get(memberId);
			userMap.remove(memberId);
			if(cm!=null){
				cm.getAsyncContext().complete();
			}
		}finally{
//			w.unlock();
		}

		
	}
	

	
    public synchronized Set<String> allKeys() {
//        r.lock();
        try { 
        	return userMap.keySet(); 
        }finally { 
//        	r.unlock(); 
        }
    }
    
	public Collection<ChatMember> allValues() {
//		r.lock();
		try {
			return userMap.values();
		} finally {
//			r.unlock();
		}

	}
    
	public synchronized void clear() {
//		w.lock();
		try {
			userMap.clear();
		} finally {
//			w.unlock();
		}
	}
	

}
